package com.zy.hospitalward_management_system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.hospitalward_management_system.pojo.*;
import com.zy.hospitalward_management_system.service.impl.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zy
 * @since 2021-01-26
 */
@Controller
public class PatientController {

    @Resource
    DrugServiceImpl drugService;

    @Resource
    PatientServiceImpl patientService;

    @Resource
    InpatientwardServiceImpl inpatientwardService;

    @Resource
    BedServiceImpl bedService;

    @Resource
    DepartmentServiceImpl departmentService;

    @Resource
    LogServiceImpl logService;

    @Resource
    DoctorServiceImpl doctorService;


    /**
     * 病人登记接口 ajax请求
     * @param patient springmvc 接收病人对象
     * @return 一些返回信息 String
     */
    @PostMapping("/patient/checkin")
    @ResponseBody
    public String patientCheckin(Patient patient){
        System.out.println("PatientController.patientCheckin");
        System.out.println(patient);

        //checkResult 传入病人对象的检查结果
        String checkResult = patientService.patientCheckinCheck(patient);

        //如果病人信息检查通过. checkResult equals ok
        if(checkResult.equals("ok")){
            //根据姓名,年龄,联系方式来检查病人表中有无此人.
            Patient Cpatient = patientService.getBaseMapper().selectOne(new QueryWrapper<Patient>()
                    .eq("patient_name", patient.getPatientName())
                    .eq("patient_age", patient.getPatientAge())
                    .eq("patient_phone", patient.getPatientPhone()));
            if(Cpatient!=null){
                return "该患者已经登记过!";
            }

            //患者住院日期为获取当前时期.
            patient.setInDate(new Date());

            //患者表插入一条记录,并更新病床表的状态.
            if(patientService.getBaseMapper().insert(patient) == 1){
                boolean result = bedService.updateBedStateById(patient.getBedId(), 1);
                if(result){
                    Doctor doctor = doctorService.getBaseMapper().selectById(patient.getDoctorId());
                    Log log = new Log(null,patient.getPatientId(),patient.getPatientName(),patient.getPatientPhone(),doctor.getDoctorName(),patient.getDoctorId(),new Date(),"住院");
                    int logResult = logService.getBaseMapper().insert(log);
                    if(logResult==1)
                        return "登记成功!";
                }
            }
            return "登记失败!";
        }

        return checkResult;
    }


    /**
     * 病人修改接口 ajax请求
     * @param patient springmvc 接收病人对象
     * @return 一些返回信息 String
     */
    @PostMapping("/patient/update")
    @ResponseBody
    public String patientUpdate(Patient patient){
        System.out.println(patient);
        Patient oldPatient = patientService.getBaseMapper().selectById(patient.getPatientId());
        //checkResult 传入病人对象的检查结果
        String checkResult = patientService.patientCheckinCheck(patient);

        //如果病人信息检查通过. checkResult equals ok
        if(checkResult.equals("ok")){
            if(patientService.updateById(patient)){
                //如果换床位了
                if(!patient.getBedId().equals(oldPatient.getBedId())){
                    bedService.updateBedStateById(oldPatient.getBedId(), 0); //老床位状态改成0
                    bedService.updateBedStateById(patient.getBedId(), 1); //新床位状态改成1
                }

                return "修改成功!";
            }else {
                return "修改失败!";
            }

        }

        return checkResult;
    }


    /**
     * 从病人管理页面 携带信息跳转回到病人详情页面
     * @param patientId 病人ID
     * @param model
     * @return
     */
    @GetMapping("/patient/info/{id}")
    public String toPatientInfo(@PathVariable("id") String patientId, Model model){
        List<Drug> drugs = drugService.getBaseMapper().selectList(null);
        List<Department> departments = departmentService.getBaseMapper().selectList(null);
        Patient patient = patientService.getBaseMapper().selectById(patientId);
        model.addAttribute("departments",departments);
        model.addAttribute("patient",patient);
        model.addAttribute("drugs",drugs);
        return "user/info/patient_info";
    }

    /**
     * 根据患者名或者联系方式进行病人管理页面的精确或模糊查询
     */
    @RequestMapping("/patient/search")
    public String patientSearch(String search,Model model){

        if(search==null||search.isEmpty()){
            model.addAttribute("msg","请输入搜索内容!");
            return "forward:/toPatientList";
        }
        search=search.trim();
        List<Patient> patients = patientService.getBaseMapper().selectList(
                new QueryWrapper<Patient>().like("patient_name", search).or().eq("patient_phone", search));
        if(!patients.isEmpty()){
            model.addAttribute("patients",patients);
            return "user/list/patient_list";
        }
        model.addAttribute("msg","未查询到相关记录!");
        return "forward:/toPatientList";
    }



    /**
     * 跳转到办理出院 info页面
     */
    @GetMapping("/toPatientCheckoutInfo/{id}")
    public String toPatientCheckoutInfo(@PathVariable("id") int id,Model model){
        Patient patient = patientService.getBaseMapper().selectById(id);
        model.addAttribute("patient",patient);

        Doctor doctor = doctorService.getBaseMapper().selectById(patient.getDoctorId());
        model.addAttribute("doctor",doctor);

        Drug drug = drugService.getBaseMapper().selectById(patient.getDrugId());
        model.addAttribute("drug",drug);

        Inpatientward inpatientward = inpatientwardService.getBaseMapper().selectById(patient.getInpatientwardId());
        model.addAttribute("inpatientward",inpatientward);

        long day = (patient.getOutDate().getTime() - patient.getInDate().getTime())/(24 * 60 * 60 * 1000);
        Double cost = (drug.getDrugPrice()+inpatientward.getInpatientwardCost())*day;
        model.addAttribute("day",day);
        model.addAttribute("cost",cost);

        return "user/info/patient_checkout_info";
    }

    /**
     * 办理出院
     */
    @PostMapping("/patientCheckOut")
    @ResponseBody
    public String patientCheckOut(int id){
        Patient patient = patientService.getBaseMapper().selectById(id);
        if(patient!=null){
            try {
                //床位状态改掉
                bedService.updateBedStateById(patient.getBedId(), 0);
                //患者表删除记录
                patientService.getBaseMapper().deleteById(patient.getPatientId());
                //记录表添加一条记录
                Doctor doctor = doctorService.getBaseMapper().selectById(patient.getDoctorId());
                Log log = new Log(null, patient.getPatientId(), patient.getPatientName(), patient.getPatientPhone(), doctor.getDoctorName(), patient.getDoctorId(), new Date(), "出院");
                int insert = logService.getBaseMapper().insert(log);
                if(insert==1){
                    return "办理成功!";
                }
            }catch (Exception e){
                e.printStackTrace();
                return "办理失败!";
            }
        }
        return "办理失败!";
    }

    /**
     * 根据患者名或者联系方式进行出院页面的模糊查询
     */
    @RequestMapping("/toPatientCheckout/search")
    public String toPatientCheckoutSearch(String search,Model model){


        if(search==null||search.isEmpty()){
            model.addAttribute("msg","请输入搜索内容!");
            return "forward:/toPatientCheckout";
        }
        search=search.trim();
        List<Patient> patients = patientService.getBaseMapper().selectList(
                new QueryWrapper<Patient>().like("patient_name", search).or().eq("patient_phone", search));
        if(!patients.isEmpty()){
            model.addAttribute("patients",patients);
            List<Department> departments = departmentService.getBaseMapper().selectList(null);
            model.addAttribute("departments",departments);
            List<Doctor> doctors = doctorService.getBaseMapper().selectList(null);
            model.addAttribute("doctors",doctors);
            return "user/patient_checkout";
        }
        model.addAttribute("msg","未查询到相关记录!");
        return "forward:/toPatientCheckout";
    }



}

